package nix.mall.order.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import nix.mall.common.pojo.NixMallResult;
import nix.mall.order.service.OrderService;
import nix.mall.pojo.Item;
import nix.mall.pojo.OrderInfo;
import nix.mall.pojo.User;
import nix.mall.utils.CookieUtils;
import nix.mall.utils.JsonUtils;

/**
 * 订单确认页Controller
 */
@Controller
public class OrderCartController {

	@Value("${CART_KEY}")
	private String CART_KEY;
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping("/order/order-cart")
	public String showOrderCart(HttpServletRequest request, Model model) {
		// 用户必须是登陆状态
		// 取用户id
		User user = (User) request.getAttribute("user");
		System.out.println(user.getUsername());
		// 根据用户信息取收货信息
		// 收货信息传递至页面
		// 从Cookie中取购物车商品列表
		List<Item> cartItemList = getCartItemList(request);
		// 传递至页面
		model.addAttribute("cartList", cartItemList);
		// 返回逻辑视图
		return "order-cart";		
	}
	
	private List<Item> getCartItemList(HttpServletRequest request) {
		// 从Cookie中取购物车商品列表
		String json = CookieUtils.getCookieValue(request, CART_KEY, true);
		if (StringUtils.isBlank(json)) {
			return new ArrayList<>();
		}
		List<Item> list = JsonUtils.jsonToList(json, Item.class);
		return list;
	}
	
	@RequestMapping(value="/order/create", method=RequestMethod.POST)
	public String createOrder(OrderInfo orderInfo, Model model) {
		// 生成订单
		NixMallResult result = orderService.createOrder(orderInfo);
		// 返回逻辑视图
		model.addAttribute("orderId", result.getData().toString());
		model.addAttribute("payment", orderInfo.getPayment());
		DateTime dateTime = new DateTime();
		dateTime = dateTime.plusDays(3);
		model.addAttribute("date", dateTime.toString("yyyy-MM-dd"));
		return "success";
	}
}
